import React, { useState, useEffect } from "react";
import { Location } from "@react-vant/icons";
import { useNavigate } from "react-router-dom";

export default function Header() {
  const navigate = useNavigate();
  const [address, setAddress] = useState("");
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // 获取位置信息
  const getLocation = async () => {
    setLoading(true);
    setError(null);

    // 检查浏览器是否支持地理定位
    if (!navigator.geolocation) {
      setError("您的浏览器不支持地理定位");
      setLoading(false);
      return;
    }

    try {
      // 使用浏览器定位
      const position = await new Promise((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(resolve, reject, {
          enableHighAccuracy: true,
          timeout: 5000,
          maximumAge: 0,
        });
      });

      const { latitude, longitude } = position.coords;

      // 使用高德地图逆地理编码服务获取地址
      const response = await fetch(
        `https://restapi.amap.com/v3/geocode/regeo?key=4da3d7c3d326f16a2d470165c3379ee0&location=${longitude},${latitude}&extensions=base`
      );
      const data = await response.json();

      if (data.status === "1" && data.regeocode) {
        setAddress(data.regeocode.formatted_address);
      } else {
        throw new Error("地址解析失败");
      }
    } catch (err) {
      console.error("定位错误:", err);

      // 如果浏览器定位失败，回退到IP定位
      try {
        const ipResponse = await fetch(
          `https://restapi.amap.com/v3/ip?key=4da3d7c3d326f16a2d470165c3379ee0`
        );
        const ipData = await ipResponse.json();

        if (ipData.status === "1") {
          setAddress(`${ipData.province}${ipData.city}`);
        } else {
          setError("获取位置信息失败");
          setAddress("");
        }
      } catch (ipErr) {
        setError("网络请求失败");
        setAddress("");
      }
    } finally {
      setLoading(false);
    }
  };

  // 组件加载时自动获取位置
  useEffect(() => {
    getLocation();
  }, []);

  const werra = (e, address) => {
    e.preventDefault();
    navigate(`/outlet/addA/?address=${address}`);
  };

  return (
    <div>
      <ul>
        <li
          style={{
            color: " grey",
            fontSize: "14px",
            height: "30px",
            lineHeight: "30px",
            margin: "20px 20px",
            textAlign: "left",
            borderBottom: "1px solid #eee",
          }}
          onClick={(event) => werra(event, address)}
        >
          <span style={{ color: "orange" }}>
            <Location style={{ fontSize: "23px", color: "#ff5435" }} />
            {address}
          </span>
        </li>
      </ul>
    </div>
  );
}
